<?php

/*
 * ping++ 支付基础
 */
namespace app\index\controller;
use think\Loader;
class Pcpay extends Base{

    const API_KEY = 'sk_live_ab1Wv5T4izf5y58480mb5GWT';

    const APP_ID_PC = 'app_mjXLiLWHSSaPPKyj';

    //订单支付
    public function orderPay(){
        try{
            require_once EXTEND_PATH . "pingpp/init.php";
            parent::__construct();
            \Pingpp\Pingpp::setApiKey(self::API_KEY);
            \Pingpp\Pingpp::setPrivateKeyPath(EXTEND_PATH . '/pingpp/your_rsa_private_key.pem');

            $user       = session('lt_user');
            if(empty($user)){
                return json(messageInfo ( '101', '请先登录，在进行操作！' ));
            }
            $o_no     = input('o_no');
            $pay_type = input('pay_type');
            $invoking                 = Loader::model('Pay','service');
            $data                     = $invoking->orderPayApi($o_no,$pay_type);
            if($data['code'] == 202){
                $Charge = \Pingpp\Charge::create($data['data']);
                $Charge_data = json_decode($Charge,true);
                $response    = messageInfo ( '202', '请求支付成功',$Charge_data) ;
            }else{
                $response =   $data;
            }
        } catch (\Exception $e) {
            $response = messageInfo ( '101', '服务器错误！' );
        }
        return json($response);
    }


    //ping ++ 异步
    public function payhooks(){
        header("Content-type:text/html;charset=utf-8");
        $raw_data  = file_get_contents('php://input');
        $headers   = $this->getRequestHeaders();
        $signature = isset($headers['X-Pingplusplus-Signature']) ? $headers['X-Pingplusplus-Signature'] : NULL;
        // 「Ping++ 公钥」
        $pub_key_path = EXTEND_PATH . 'pingpp/your_rsa_public.pem';
        $result = $this->verify_signature($raw_data, $signature, $pub_key_path);
        if ($result === 1) {
            // 验证通过
           $event = json_decode($raw_data, true);
            if ($event['type'] == 'charge.succeeded') {//支付成功
                $charge = $event['data']['object'];
                $o_third_id    = $charge['id']; //；ping++ 订单
                $channel       = $charge['channel'];//支付类型
                $order_no      = $charge['order_no']; //订单号
                $invoking                 = Loader::model('Pay','service');
                $data                     = $invoking->payhooksApi($o_third_id,$channel,$order_no);
                $date           = date('Y-m-d H:i:s');
                if($data == true){
                    $prefix = '数据写入成功'.$date;
                    create_file("./uploads/log_pay_succeed.txt", "",$prefix.$raw_data);
                    return http_response_code(200);
                }else{
                    $prefix = '数据写入失败'.$date;
                    create_file("./uploads/log_pay_succeed.txt", "",$prefix.$raw_data);
                    return http_response_code(400);
                }
            }else{
                create_file("./uploads/log_pay_error.txt", "",date('Y-m-d H:i:s').$raw_data);
                return http_response_code(200);
            }
        } elseif ($result === 0) {
            create_file("./uploads/log_pay_error.txt", "",date('Y-m-d H:i:s').'verification failed');
            return http_response_code(400);
            exit;
        } else {
            create_file("./uploads/log_pay_error.txt", "",date('Y-m-d H:i:s').'verification error');
            return http_response_code(400);
            exit;
        }
    }

    public  function getRequestHeaders()
    {
        if (function_exists('getallheaders')) {
            return getallheaders();
        }
        $headers = array();
        foreach ($_SERVER as $name => $value) {
            if (substr($name, 0, 5) == 'HTTP_') {
                $headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;
            }
        }
        return $headers;
    }


    // 验证 webhooks 签名方法
   public function verify_signature($raw_data, $signature, $pub_key_path) {
        $pub_key_contents = file_get_contents($pub_key_path);
        // php 5.4.8 以上，第四个参数可用常量 OPENSSL_ALGO_SHA256
        return openssl_verify($raw_data, base64_decode($signature), $pub_key_contents, 'sha256');
    }



}
